package com.wnxy.portal.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import com.wnxy.portal.api.MemberClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Proxy;

@RestController
@RequestMapping("/portal/feign")
@Slf4j
//@DefaultProperties(defaultFallback = "errorFallback")//指定默认降级方法
public class PortalFeignController {

    // 注入feign客户端代理对象
    @Autowired
    private MemberClient memberClient;

    @GetMapping
    public String findMember() {
        // 通过feign实现远程调用: HttpUrlConnection 发送的网络请求
        return memberClient.findOne("100");
    }

    @GetMapping("timeout")
    //@HystrixCommand
    public String findTimeout() {
        return memberClient.findTimeout();
    }

    //public String errorFallback(){
    //    return "降级方法";
    //}

    @GetMapping("/find/{id}")
    @HystrixCommand(fallbackMethod = "errorFallback",commandProperties = {
            // 是否开启断路器
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ENABLED,value = "true"),
                    // 请求错误率大于 50% 就启动熔断器
                    @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE,value = "50"),
                    // 默认10秒内访问接口失败达到20次，打开断路器，触发熔断； 为了方便测试，这里修改10秒内错误达到10次触发熔断。
                    @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD,value = "10"),
                    //断路多久以后开始尝试是否恢复，默认5s
                    @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS,value = "10000")
    })
    public String findMemberById(@PathVariable("id")Integer id) {
        if (id<0) {
            throw new RuntimeException("id不能为负数");
        }
        return Thread.currentThread().getName() + " 调用成功";
    }

    // 默认降级方法，返回string
    public String errorFallback(@PathVariable("mid")Integer mid){
        return "默认降级方法";
    }
}
